package org.hxyjs.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.hxyjs.aop.SystemMail;
import org.hxyjs.dto.DTO;
import org.hxyjs.entity.OrderForm;
import org.hxyjs.entity.User;
import org.hxyjs.page.PageInfo;
import org.hxyjs.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@CrossOrigin
@Controller //@Controller注解是用spring容器生成 对象 默认对象名 userController
@RequestMapping("/userController") //@RequestMapping 用户请求查找该资源使用的名字 网名 默认  /userController
public class UserController {
	@Resource
	UserService userService;
	@RequestMapping("/getAllUser")
	@ResponseBody //把方法的返回值按json转换之后 输出到浏览器
	public DTO<User> getAllUsers() throws Exception{
		System.out.println("查询全部");
		return userService.getAllUsers();
	}

	@RequestMapping("/getUserByUno/{uno}")
	@ResponseBody //把方法的返回值按json转换之后 输出到浏览器
	public DTO<User> getUserByUno(@PathVariable("uno") String uno) throws Exception{
		System.out.println(uno + "查询成功");
		return userService.getUserByUno(uno);
	}
	@SystemMail(op = "User:addUser",queueName = "family.mail",module = "用户管理",methods = "用户注册")
	@RequestMapping("/addUserByUno")
	@ResponseBody
	public DTO<User> addUserByUno(@RequestBody User user) throws Exception{//如何从页面传入参数到方法 用这个注解绑定变量@PathVariable
		System.out.println("增加成功");
		return userService.addUserByUno(user);
	}

	@RequestMapping("/deleteUser/{uno}")
	@ResponseBody
	public DTO<User> deleteUser(@PathVariable("uno") String uno) throws Exception{//如何从页面传入参数到方法 用这个注解绑定变量@PathVariable
		System.out.println(uno+"删除成功");
		return userService.deleteUser(uno);
	}

	@RequestMapping("/getUsersWithOrders/{uno}")
	@ResponseBody
	public DTO<User> getUsersWithOrders(@PathVariable("uno") String uno,HttpServletRequest request,HttpServletResponse response) throws Exception{//如何从页面传入参数到方法 用这个注解绑定变量@PathVariable
		System.out.println("查询学生选课111");
		DTO<User> dto = userService.getUsersWithOrders(uno);
		saveSelectCourseCookieProcess(dto.getT(),request,response);
		return  dto;
	}
	@RequestMapping("/updateUser")
	@ResponseBody
	public DTO<User> updateUser(@RequestBody User user) throws Exception{//如何从页面传入参数到方法 用这个注解绑定变量@PathVariable
		System.out.println("修改成功");
		return userService.updateUser(user);
	}
	@RequestMapping("/getUsersByPage")
	@ResponseBody
	public DTO<User> getUsersByPage(PageInfo pageInfo) throws Exception {//如何从页面传入参数到方法 用这个注解绑定变量@PathVariable
		System.out.println("查询分页");
		return userService.getUsersByPage(pageInfo);
	}
	public DTO<User> saveSelectCourseCookieProcess(User user, HttpServletRequest request, HttpServletResponse response) throws JsonProcessingException, UnsupportedEncodingException {
		//cookie是以key value形式存放在浏览器的文本
		DTO dto = new DTO(200,"cookie保存成功");
//		if(user!=null&&user.getUno()!=null) {
//			ObjectMapper objectMapper = new ObjectMapper();
//			Optional<List<OrderForm>> orderFormsOp = Optional.ofNullable(user.getOrderForms());
//			List<OrderForm> orderForms = null;
//			if (orderFormsOp.isPresent()&&orderFormsOp.get().size()>0) {
//				orderForms = new ArrayList<OrderForm>(user.getOrderForms());
//
//				for (OrderForm orderForm : user.getOrderForms()) {
//					Cookie orderFormsCookie = new Cookie("user" + user.getUno() + "_" + orderForm.getUrno(), URLEncoder.encode(objectMapper.writeValueAsString(orderForm), "UTF-8"));
//
//					//userCookie.setMaxAge(30*24*60*60);   //存活期为一个月 30*24*60*60
//					orderFormsCookie.setPath("/");
//					orderFormsCookie.setDomain("localhost");
//					orderFormsCookie.setMaxAge(2 * 24 * 60 * 60);   //存活期为2天 2*24*60*60
//					response.addCookie(orderFormsCookie);
//
//				}
//			}
//			user.setOrderForms(null);
//			Cookie userCookie = new Cookie("user" + user.getUno(), URLEncoder.encode(objectMapper.writeValueAsString(user), "UTF-8"));
//			userCookie.setPath("/");
//			userCookie.setDomain("localhost");
//			userCookie.setMaxAge(2 * 24 * 60 * 60);   //存活期为2天 2*24*60*60
//			response.addCookie(userCookie);
//			user.setOrderForms(orderForms);
//		}else{
//			dto.setCode(406);
//			dto.setMsg("缺少必要的参数，非法操作");
//		}
		return dto;
	}

	/**
	 * 根据用户编号查询cookie中有没有相对应的用户信息
	 * @param uno
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getOrderCookie/{uno}")
	@ResponseBody
	public DTO<User> getOrderCookie(@PathVariable("uno") String uno, HttpServletRequest request, HttpServletResponse response) throws Exception{
		//cookie是以key value形式存放在浏览器的文本
		ObjectMapper objectMapper = new ObjectMapper();
		DTO dto = new DTO(200, "cookie订单获取成功");
		Cookie[] cookies = request.getCookies();
		User user = null;
		System.out.println("--------------");
		if(Optional.ofNullable(cookies).isPresent()){
			List<OrderForm> orderForms = new ArrayList<OrderForm>();

			for(Cookie cookie :cookies){
				if(cookie.getName().indexOf("user" + uno+"_")>=0){
					OrderForm orderForm = objectMapper.readValue(URLDecoder.decode(cookie.getValue()), OrderForm.class);
					orderForms.add(orderForm);
				}
				if(cookie.getName().equals("user" + uno)){
					user = objectMapper.readValue(URLDecoder.decode(cookie.getValue()), User.class);
				}

			}

			if(Optional.ofNullable(user).isPresent()){
				user.setOrderForms(orderForms);
				dto.setT(user);
			}
		}if(!Optional.ofNullable(user).isPresent()){
			dto.setCode(404);
			dto.setMsg("没有cookie");
		}


		return dto;
	}
	@RequestMapping("/activate/{uno}")
	@ResponseBody
	public DTO<User> activate(@PathVariable("uno") String uno) throws Exception{

		return userService.activate(uno);
	}

	@SystemMail(op = "User:lettory",queueName = "family.mail",module = "中奖",methods = "中奖信息")
	@RequestMapping("/lettory/{uno}/{giftName}")
	@ResponseBody
	public DTO<User> lettory(@PathVariable("uno") String uno,@PathVariable("giftName")String giftName) throws Exception{

		return userService.lettory(uno,giftName);
	}



}
